package com.rich.house.service.impl;

import java.util.ArrayList;
import java.util.Date;

import com.alipay.api.AlipayApiException;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.rich.common.entity.*;
import com.rich.common.result.ResultData;
import com.rich.common.util.IdWorker;
import com.rich.house.feign.AliPayFeign;
import com.rich.house.mapper.BrokerMapper;
import com.rich.house.mapper.HouseImgMapper;
import com.rich.house.mapper.HouseMapper;
import com.rich.house.service.HouseService;
import com.rich.house.utils.FreeMark;
import com.rich.house.vo.HouseAndHouseImgVo;
import com.rich.house.utils.ElasticSearchUtil;
import com.rich.house.vo.HouseAndVillageVo;
import com.rich.house.vo.HouseSearchVo;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

/**
 * @Package: com.rich.house.service.impl
 * @Author: 张dy
 * @Date: Created in 2021/8/13 下午 7:36
 */
@Service
public class HouseServiceImpl implements HouseService {

    @Autowired
    private HouseMapper houseMapper;
    @Autowired
    private BrokerMapper brokerMapper;
    @Autowired
    private HouseImgMapper houseImgMapper;
    @Autowired
    private AliPayFeign aliPayFeign;
    /**
     * es客户端
     */
    @Autowired
    private RestHighLevelClient restHighLevelClient;
    @Autowired
    private ElasticSearchUtil elasticSearchUtil;

    @Override
    public ResultData getHouseList(HouseSearchVo houseSearchVo) {
        PageHelper.startPage(houseSearchVo.getPage(), houseSearchVo.getLimit());
        List<TbHouse> houses = houseMapper.getHouseList(houseSearchVo);
        List<HouseAndHouseImgVo> houseAndHouseImgVoList = new ArrayList<>();
        //遍历
        houses.forEach(item->{
            String id = item.getId();
            TbHouseImg houseImg =houseImgMapper.findById(id);
            houseAndHouseImgVoList.add(new HouseAndHouseImgVo(item,houseImg));
        });
        PageInfo<HouseAndHouseImgVo> map = new PageInfo<>(houseAndHouseImgVoList);
        return new ResultData(map.getList(), map.getTotal());
    }

    /**
     * 经纪人端新房列表
     * @param houseSearchVo
     * @return
     */
    @Override
    public ResultData searchHouse(HouseSearchVo houseSearchVo) throws IOException {
        //获取条件对象
        SearchSourceBuilder sourceBuilder = getSearchSourceBuilder(houseSearchVo);
        //分页
        if (0==houseSearchVo.getPage()){
            houseSearchVo.setPage(1);

        }
        //计算起始下标
        int form = (houseSearchVo.getPage()-1)*houseSearchVo.getLimit();
        return elasticSearchUtil.searchListData(
                "rich_house",
                sourceBuilder,
                houseSearchVo.getLimit(),
                form,
                null,
                "sort",
                "title");
    }

    /**
     * 构件条件对象
     * @param houseSearchVo
     * @return
     */
    private SearchSourceBuilder getSearchSourceBuilder(HouseSearchVo houseSearchVo,QueryBuilder... querys) {
        //构件条件对象
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        //添加条件
        //创建复合查询对象
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        //精确查找
        if (houseSearchVo.getAddressOne()!=null){
            TermQueryBuilder addressOne = QueryBuilders.termQuery("address_one", houseSearchVo.getAddressOne());
            boolQuery.must(addressOne);
        }
        if (houseSearchVo.getAddressTwo()!=null){
            TermQueryBuilder addressTwo = QueryBuilders.termQuery("address_two", houseSearchVo.getAddressTwo());
            boolQuery.must(addressTwo);
        }
        if (houseSearchVo.getAddressThree()!=null){
            TermQueryBuilder addressThree = QueryBuilders.termQuery("address_Three", houseSearchVo.getAddressThree());
            boolQuery.must(addressThree);
        }
        if (houseSearchVo.getHouseType()!=null){
            TermQueryBuilder houseType = QueryBuilders.termQuery("house_type", houseSearchVo.getHouseType());
            boolQuery.must(houseType);
        }
        if (houseSearchVo.getRoom()!=null){
            TermQueryBuilder room = QueryBuilders.termQuery("room", houseSearchVo.getRoom());
            boolQuery.must(room);
        }
        if (houseSearchVo.getCheckTrue()!=null){
            TermQueryBuilder checkTrue = QueryBuilders.termQuery("check_true", houseSearchVo.getCheckTrue());
            boolQuery.must(checkTrue);
        }
        //选型【0-整租 1-合租】
        if (houseSearchVo.getModel()!=null){
            TermQueryBuilder model = QueryBuilders.termQuery("model", houseSearchVo.getModel());
            boolQuery.must(model);
        }
        //朝向【0-东 1-西 2-南 3-北 4-南北】
        if (houseSearchVo.getOrientation()!=null){
            TermQueryBuilder orientation = QueryBuilders.termQuery("orientation", houseSearchVo.getOrientation());
            boolQuery.must(orientation);
        }
        //房源类型【0-新房 1-二手房 2-出租房】
        if (houseSearchVo.getHouseForm()!=null){
            TermQueryBuilder houseForm = QueryBuilders.termQuery("house_form", houseSearchVo.getHouseForm());
            boolQuery.must(houseForm);
        }
        //范围查询
        RangeQueryBuilder sumPrice = QueryBuilders.rangeQuery("sum_price");
        if (houseSearchVo.getStartPrice()!=null){
            sumPrice.gte(houseSearchVo.getStartPrice());
        }
        if (houseSearchVo.getEndPrice()!=null){
            sumPrice.lte(houseSearchVo.getEndPrice());
        }
        boolQuery.should(sumPrice);
        //模糊查询
        if (houseSearchVo.getField()!=null){
            MultiMatchQueryBuilder multiMatchQueryBuilder = QueryBuilders.multiMatchQuery(houseSearchVo.getField(), "title", "selling_point", "mentality", "content", "village_name");
            boolQuery.should(multiMatchQueryBuilder);
        }
        //构件高量
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("title");
        highlightBuilder.preTags("<span style='color:red'>");
        highlightBuilder.postTags("</span>");
        //添加额外 条件对象
        if (querys!=null){
            for (QueryBuilder query : querys) {
                boolQuery.must(query);
            }
        }
        //加入条件对象
        sourceBuilder.query(boolQuery);
        sourceBuilder.highlighter(highlightBuilder);
        return sourceBuilder;
    }

    @Override
    public ResultData findHouseAll(HouseSearchVo houseSearchVo) {
        PageHelper.startPage(houseSearchVo.getPage(),houseSearchVo.getLimit());
        List<HouseAndVillageVo> houses = houseMapper.findHouseAll(houseSearchVo);
        PageInfo<HouseAndVillageVo> pageInfo = new PageInfo<>(houses);
        return new ResultData(pageInfo.getList(),pageInfo.getTotal());
    }

    @Override
    public TbHouse findById(String id) {
        //创建 freeMarker对象
        FreeMark freeMark = new FreeMark();
        TbHouse byId = houseMapper.findById(id);
        try {
            //生成静态页面
            freeMark.test(byId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return byId;
    }

    @Override
    public String addHouse(TbHouse house, Long userId, String status) throws AlipayApiException {
        //初始化信息
        IdWorker idWorker = new IdWorker();
        house.setId(String.valueOf(idWorker.nextId()));
        house.setCreatTime(new Date());
        house.setUpdateTime(new Date());
        house.setStatus(status);
        house.setIsDelete("1");
        //经纪人房源加 1
        brokerMapper.updHouseNum(house.getHouseForm(),userId);
        houseMapper.addHouse(house);
        //支付

        String s = aliPayFeign.payOrder(Long.parseLong(house.getId()));
        return s;
    }

    @Override
    public void updHouse(TbHouse house) {
        house.setUpdateTime(new Date());
        houseMapper.updHouse(house);
    }


    @Override
    public void addHouseBroker(String id, Long brokerId) {
        //获取房源信息
        TbHouse byId = houseMapper.findById(id);
        //房源类型
        Integer houseForm = byId.getHouseForm();

        //经纪人房源加 1
        brokerMapper.updHouseNum(houseForm,brokerId);
        //指定经纪人
        houseMapper.addHouseBroker(id,brokerId);
    }

    @Override
    public void updHouseStatus(String id, String status) {
        houseMapper.updHouseStatus(id,status);
    }

    @Override
    public void updateDeteleById(String id) {
        houseMapper.updateDeteleById(id);
    }


}
